package main.java.com.healthy.dao.impl;

import main.java.com.healthy.dao.UserDAO;
import main.java.com.healthy.entity.User;
import main.java.com.healthy.util.FileUtil;
import main.java.com.healthy.util.PasswordUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 用户数据访问实现类
 */

public class UserDAOImpl implements UserDAO {

    private static final String USER_FILE = "data/users.dat";
    private List<User> users;

    public UserDAOImpl() {
        loadUsers();
    }

    @Override
    public boolean addUser(User user) {
        try {
            // 生成唯一用户ID
            if (user.getUserId() == null || user.getUserId().isEmpty()) {
                user.setUserId(generateUserId());
            }

            // 检查用户名是否已存在
            if (userExists(user.getUsername())) {
                System.out.println("用户名已存在: " + user.getUsername());
                return false;
            }

            users.add(user);
            return saveUsers();
        } catch (Exception e) {
            System.err.println("添加用户失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean updateUser(User user) {
        try {
            for (int i = 0; i < users.size(); i++) {
                if (users.get(i).getUserId().equals(user.getUserId())) {
                    users.set(i, user);
                    return saveUsers();
                }
            }
            return false;
        } catch (Exception e) {
            System.err.println("更新用户失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean deleteUser(String userId) {
        try {
            boolean removed = users.removeIf(user -> user.getUserId().equals(userId));
            if (removed) {
                return saveUsers();
            }
            return false;
        } catch (Exception e) {
            System.err.println("删除用户失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public User getUserById(String userId) {
        return users.stream()
                .filter(user -> user.getUserId().equals(userId))
                .findFirst()
                .orElse(null);
    }

    @Override
    public User getUserByUsername(String username) {
        return users.stream()
                .filter(user -> user.getUsername().equals(username))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<User> getAllUsers() {
        return new ArrayList<>(users);
    }

    @Override
    public boolean userExists(String username) {
        return users.stream()
                .anyMatch(user -> user.getUsername().equals(username));
    }

    @Override
    public boolean validatePassword(String username, String password) {
        User user = getUserByUsername(username);
        if (user != null) {
            return PasswordUtil.checkPassword(password, user.getPassword());
        }
        return false;
    }

    @Override
    public boolean updatePassword(String userId, String newPassword) {
        try {
            User user = getUserById(userId);
            if (user != null) {
                String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
                user.setPassword(encryptedPassword);
                return updateUser(user);
            }
            return false;
        } catch (Exception e) {
            System.err.println("更新密码失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 生成唯一用户ID
     */
    private String generateUserId() {
        return "USER_" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 加载用户数据
     */
    @SuppressWarnings("unchecked")
    private void loadUsers() {
        try {
            Object data = FileUtil.readObject(USER_FILE);
            if (data instanceof List) {
                users = (List<User>) data;
            } else {
                users = new ArrayList<>();
                // 初始化默认管理员用户
                initializeDefaultUsers();
            }
        } catch (Exception e) {
            System.err.println("加载用户数据失败: " + e.getMessage());
            users = new ArrayList<>();
            initializeDefaultUsers();
        }
    }

    /**
     * 保存用户数据
     */
    private boolean saveUsers() {
        try {
            return FileUtil.writeObject(USER_FILE, users);
        } catch (Exception e) {
            System.err.println("保存用户数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 初始化默认用户
     */
    private void initializeDefaultUsers() {
        User admin = new User(
                "USER_ADMIN",
                "admin",
                PasswordUtil.encryptPassword("123456"),
                175.0,
                70.0,
                "男",
                30,
                "中度活动",
                "维持"
        );
        admin.setEmail("admin@healthdiet.com");
        users.add(admin);
        saveUsers();
    }
}